<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\annotations\parsers;

#use \ReflectionException;

class ConstantValueParserImpl extends ConstantValueParser
{
	/**
	 * @var array<string,mixed>
	 */
	protected static $constantToValueMap = array(
		'null'  => null,
		'true'  => true,
		'yes'   => true,
		'on'    => true,
		'false' => false,
		'no'    => false,
		'off'   => false,
	);
	
	/**
	 * @param  string $value
	 * @return mixed
	 * @throws ParserException
	 */
	public function parseConstantValue($value)
	{
		if (is_numeric($value) || ($value[0] === '"' && substr($value, -1) === '"'))
		{
			$result = '';
			
			eval(
				'$result = ' . preg_replace('#((?!\\\\)\$)#', '\\\\$', $value) . ';'
			);
			
			return $result;
		}
		
		$key = strtolower($value);
		
		if (array_key_exists($key, self::$constantToValueMap))
		{
			return self::$constantToValueMap[$key];
		}
		
		if (strtolower(substr($value, -6)) === '.class')
		{
			try
			{
				return new ReflectionClass(
					str_replace('.', T_NS_SEPARATOR, substr($value, 0, -6))
				);
			}
			catch (ReflectionException $x)
			{
				throw new ParserException(sprintf(
					'Use of undefined class [%s].', $value
				));
			}
		}
		
		$value = str_replace('.', T_NS_SEPARATOR, $value);
		
		if (!defined($value))
		{
			throw new ParserException(sprintf(
				'Use of undefined constant [%s].', $value
			));
		}
		
		return constant($value);
	}
}